package com.fanrui.code.socket.netty.core;

import java.net.SocketAddress;

import com.fanrui.code.util.logger.Stdout;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandler;
import io.netty.channel.ChannelPromise;

public class OutboundExceptionLogHandler implements ChannelOutboundHandler {

	@Override
	public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		promise.addListener(new ChannelFutureListener() {

			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				if (!future.isSuccess()) {
					Stdout.GET().error("出站异常", future.cause());
				}
			}
		});
		ctx.write(msg, promise); 
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.fireExceptionCaught(cause); 
	}

	@Override
	public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception {
		ctx.bind(localAddress, promise);
	}

	@Override
	public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
			ChannelPromise promise) throws Exception {
		ctx.connect(remoteAddress, localAddress, promise); 
	}

	@Override
	public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
		ctx.disconnect(promise); 
	}

	@Override
	public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
		ctx.close(promise); 
	}

	@Override
	public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
		ctx.deregister(promise); 
	}

	@Override
	public void read(ChannelHandlerContext ctx) throws Exception {
		ctx.read(); 
	}

	@Override
	public void flush(ChannelHandlerContext ctx) throws Exception {
		ctx.flush(); 
	}
}

